// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import {
	TOKENNAME,
	HTTP_REQUEST_URL
} from '../config/app.js';
import store from '../store';
import {
	pathToBase64
} from '@/plugin/image-tools/index.js';
// #ifdef APP-PLUS
import permision from "./permission.js"
// #endif
export default {
	/**
	 * opt  object | string
	 * to_url object | string
	 * 例:
	 * this.Tips('/pages/test/test'); 跳转不提示
	 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
	 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
	 * tab=1 一定时间后跳转至 table上
	 * tab=2 一定时间后跳转至非 table上
	 * tab=3 一定时间后返回上页面
	 * tab=4 关闭所有页面，打开到应用内的某个页面
	 * tab=5 关闭当前页面，跳转到应用内的某个页面
	 */
	Tips: function(opt, to_url) {
		if (typeof opt == 'string') {
			to_url = opt;
			opt = {};
		}
		let title = opt.title || '',
			icon = opt.icon || 'none',
			endtime = opt.endtime || 2000,
			success = opt.success;
		if (title) uni.showToast({
			title: title,
			icon: icon,
			duration: endtime,
			success
		})
		if (to_url != undefined) {
			if (typeof to_url == 'object') {
				let tab = to_url.tab || 1,
					url = to_url.url || '';
				switch (tab) {
					case 1:
						//一定时间后跳转至 table
						setTimeout(function() {
							uni.navigateTo({
								url: url
							})
						}, endtime);
						break;
					case 2:
						//跳转至非table页面
						setTimeout(function() {
							uni.navigateTo({
								url: url,
							})
						}, endtime);
						break;
					case 3:
						//返回上页面
						setTimeout(function() {
							// #ifndef H5
							uni.navigateBack({
								delta: parseInt(url),
							})
							// #endif
							// #ifdef H5
							history.back();
							// #endif
						}, endtime);
						break;
					case 4:
						//关闭所有页面，打开到应用内的某个页面
						setTimeout(function() {
							uni.reLaunch({
								url: url,
							})
						}, endtime);
						break;
					case 5:
						//关闭当前页面，跳转到应用内的某个页面
						setTimeout(function() {
							uni.redirectTo({
								url: url,
							})
						}, endtime);
						break;
				}

			} else if (typeof to_url == 'function') {
				setTimeout(function() {
					to_url && to_url();
				}, endtime);
			} else {
				//没有提示时跳转不延迟
				setTimeout(function() {
					uni.navigateTo({
						url: to_url,
					})
				}, title ? endtime : 0);
			}
		}
	},
	secondToDate(result, needYear, monthText, dayText, hourText, minText) {
		let date = new Date(result * 1000)
		var o = {
			"Y": date.getFullYear(),
			"M": (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1, //月份 
			"d": date.getDate() < 10 ? "0" + date.getDate() : date.getDate(), //日 
			"h": date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //小时 
			"m": date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(), //分 
			"s": date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(), //秒 
			"q": Math.floor((date.getMonth() + 3) / 3), //季度 
			"S": date.getMilliseconds() //毫秒 
		};
		if (needYear) {
			return o.Y + monthText + o.M + dayText + o.d + hourText + o.h + minText + o.m
		} else {
			return o.M + dayText + o.d + hourText + o.h + minText + o.m
		}
	},
	/**
	 * 移除数组中的某个数组并组成新的数组返回
	 * @param array array 需要移除的数组
	 * @param int index 需要移除的数组的键值
	 * @param string | int 值
	 * @return array
	 * 
	 */
	ArrayRemove: function(array, index, value) {
		const valueArray = [];
		if (array instanceof Array) {
			for (let i = 0; i < array.length; i++) {
				if (typeof index == 'number' && array[index] != i) {
					valueArray.push(array[i]);
				} else if (typeof index == 'string' && array[i][index] != value) {
					valueArray.push(array[i]);
				}
			}
		}
		return valueArray;
	},
	/**
	 * 生成海报获取文字
	 * @param string text 为传入的文本
	 * @param int num 为单行显示的字节长度
	 * @return array 
	 */
	textByteLength: function(text, num) {
		let strLength = 0;
		let rows = 1;
		let str = 0;
		let arr = [];
		for (let j = 0; j < text.length; j++) {
			if (text.charCodeAt(j) > 255) {
				strLength += 2;
				if (strLength > rows * num) {
					strLength++;
					arr.push(text.slice(str, j));
					str = j;
					rows++;
				}
			} else {
				strLength++;
				if (strLength > rows * num) {
					arr.push(text.slice(str, j));
					str = j;
					rows++;
				}
			}
		}
		arr.push(text.slice(str, text.length));
		return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
	},
	/**
	 * 获取分享海报
	 * @param array arr2 海报素材
	 * @param string store_name 素材文字
	 * @param string price 价格
	 * @param string ot_price 原始价格
	 * @param function successFn 回调函数
	 * 
	 * 
	 */
	PosterCanvas: function(fontColor, themeColor, siteName, arr2, store_name, price, ot_price, successFn) {
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);


		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		ctx.fillStyle = '#fff';
		ctx.fillRect(0, 0, 750, 1300);
		uni.getImageInfo({
			src: arr2[0],
			success: function(res) {
				console.log("测试数据画布", res)
				const WIDTH = res.width;
				const HEIGHT = res.height;
				ctx.drawImage(res.path, 0, 0, 750, 1300);
				ctx.save();
				// ctx.setFillStyle(themeColor);
				ctx.fillRect(0, 0, WIDTH, 108);
				ctx.setFontSize(33)
				ctx.setFillStyle('#fff');
				ctx.setTextAlign('center');
				ctx.fillText('品牌官方 · 交易保障 · 优质口碑 · 售后无忧', WIDTH / 2, 65);
				ctx.save();
				ctx.drawImage(arr2[1], 32, 141, 685, 685);
				ctx.save();
				ctx.setFillStyle(themeColor);
				ctx.fillRect(32, 847, 85, 40);
				ctx.setFontSize(30)
				ctx.setFillStyle('#fff');
				ctx.setTextAlign('left');
				ctx.fillText('商城', 43, 878);
				ctx.save();
				ctx.setFontSize(36)
				ctx.setFillStyle('#000');
				ctx.fillText(siteName, 140, 880);
				ctx.save();

				const CONTENT_ROW_LENGTH = 36;
				let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name,
					CONTENT_ROW_LENGTH);
				if (contentRows > 2) {
					contentRows = 2;
					let textArray = contentArray.slice(0, 2);
					textArray[textArray.length - 1] += '...';
					contentArray = textArray;
				}
				ctx.setTextAlign('left');
				ctx.setFontSize(36);
				ctx.setFillStyle('#000');
				let contentHh = 36;
				for (let m = 0; m < contentArray.length; m++) {
					if (m) {
						ctx.fillText(contentArray[m], 30, 955 + contentHh * m + 18);
					} else {
						ctx.fillText(contentArray[m], 30, 955 + contentHh * m);
					}
				}
				ctx.save();
				ctx.setTextAlign('left')
				ctx.setFontSize(32);
				ctx.setFillStyle('#999');
				ctx.fillText('￥' + ot_price, 30, 1040 + contentHh);
				var underline = function(ctx, text, x, y, size, color, thickness, offset) {
					var width = ctx.measureText(text).width;

					switch (ctx.textAlign) {
						case "center":
							x -= (width / 2);
							break;
						case "right":
							x -= width;
							break;
					}

					y += size + offset;

					ctx.beginPath();
					ctx.strokeStyle = color;
					ctx.lineWidth = thickness;
					ctx.moveTo(x, y);
					ctx.lineTo(x + width, y);
					ctx.stroke();
				}
				underline(ctx, '￥' + ot_price, 30, 1032, 32, '#999', 2, 0);
				ctx.save();
				ctx.setTextAlign('left')
				ctx.setFontSize(55);
				ctx.setFillStyle(fontColor);
				ctx.fillText('￥' + price, 20, 1110 + contentHh);
				ctx.save();
				ctx.setFillStyle('#F5F5F5');
				ctx.fillRect(0, 1200, WIDTH, 113);
				ctx.setFontSize(30);
				ctx.setFillStyle('#999');
				ctx.fillText('长按识别图中的二维码查看商品详情', 26, 1263);
				ctx.save();
				let r = 80;
				let d = r * 2;
				let cx = 565;
				let cy = 1112;
				ctx.arc(cx + r, cy + r, r, 0, 2 * Math.PI);
				ctx.drawImage(arr2[2], cx, cy, d, d);
				ctx.restore();
				// ctx.setTextAlign('left')
				// ctx.setFontSize(28);
				// ctx.setFillStyle('#999');
				// ctx.fillText('长按或扫描查看', 490, 1030 + contentHh);
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						fileType: 'png',
						// destWidth: WIDTH,
						// destHeight: HEIGHT,
						success: function(res) {
							uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},
	fillRoundRect: function(cxt, x, y, width, height, radius, /*optional*/ fillColor) {
		//圆的直径必然要小于矩形的宽高        
		let that = this;
		if (2 * radius > width || 2 * radius > height) {
			return false;
		}

		cxt.save();
		cxt.translate(x, y);
		//绘制圆角矩形的各个边  
		that.drawRoundRectPath(cxt, width, height, radius);
		cxt.fillStyle = fillColor || "#000"; //若是给定了值就用给定的值否则给予默认值  
		cxt.fill();
		cxt.restore();
	},
	strokeRoundRect: function(cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
		//圆的直径必然要小于矩形的宽高
		let that = this;
		if (2 * radius > width || 2 * radius > height) {
			return false;
		}

		cxt.save();
		cxt.translate(x, y);
		//绘制圆角矩形的各个边  
		that.drawRoundRectPath(cxt, width, height, radius);
		cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2  
		cxt.strokeStyle = strokeColor || "#000";
		cxt.stroke();
		cxt.restore();
	},
	drawRoundRectPath: function(cxt, width, height, radius) {
		cxt.beginPath(0);
		//从右下角顺时针绘制，弧度从0到1/2PI  
		cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

		//矩形下边线  
		cxt.lineTo(radius, height);

		//左下角圆弧，弧度从1/2PI到PI  
		// cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
		// cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

		//矩形左边线  
		cxt.lineTo(0, height);

		//左上角圆弧，弧度从PI到3/2PI  
		cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

		//上边线  
		cxt.lineTo(width - radius, 0);

		//右上角圆弧  
		cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

		//右边线  
		cxt.lineTo(width, height - radius);
		cxt.closePath();
	},
	PosterCanvas1: function(fontColor, themeColor, siteName, arr2, store_name, price, ot_price, uc_cha, arr3,
		successFn) {
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		uni.getImageInfo({
			src: arr2[0],
			success: function(res) {
				const WIDTH = res.width;
				const HEIGHT = res.height;
				ctx.drawImage(res.path, 0, 0, 750, 1300);
				ctx.save();
				ctx.drawImage(arr2[4], 147, 32, 50, 50);
				ctx.save();
				ctx.setFillStyle('#fff');
				ctx.setTextAlign('center');
				ctx.setFontSize(33)
				ctx.fillText('您的好友刚刚分享了好货～', 750 / 2 + 42, 71);
				ctx.save();
				ctx.setFillStyle('#fff');
				ctx.setFontSize(33);
				ctx.setTextAlign('center');
				ctx.fillText(store_name, 750 / 2, 150);
				ctx.save();
				ctx.drawImage(arr2[1], 55, 230, 446 * 1.425, 446 * 1.3);
				let h = arr3.length == 0 ? 970 : 920;
				ctx.setFontSize(40);
				ctx.setFillStyle('#F22718');
				ctx.fillText('￥', 80, h);
				ctx.save();
				ctx.setFontSize(60);
				ctx.font = 'normal bold 60px sans-serif';
				ctx.fillText(price, 183, h);
				ctx.save();
				if (uc_cha > 0) {
					ctx.setFillStyle('#EB4D42');
					let w = ctx.measureText(uc_cha).width;
					// ctx.fillRect(300, h - 60, w + 130, 60);
					that.fillRoundRect(ctx, 300, h - 50, w + 130, 60, 12, '#EB4D42')
					ctx.save();
					ctx.setFontSize(33);
					ctx.setFillStyle('#fff');
					ctx.font = 'normal normal 33px sans-serif';
					ctx.fillText('UC立减 ' + uc_cha + '元', 424, h - 6, 600);
					ctx.save();
				}
				if (arr3.length > 0) {
					let name = '';
					for (let m = 0; m < arr3.length; m++) {
						if (arr3.length == 1) {
							name += arr3[m].name;
						} else {
							name += arr3[m].name + '；';
						}
					}

					// ctx.setFillStyle('#EB4D42');
					let width = ctx.measureText(name).width;

					if (width > 600) {
						let len = name.length;
						while (width > 600 && len-- > 0) {
							name = name.slice(0, len);
							width = ctx.measureText(name).width;
						}
						name = name + '...'
					}
					console.log("文字宽度==", width, name)
					that.fillRoundRect(ctx, 55, 950, width + 20, 55, 8, 'rgba(255,71,120,0.08)')
					ctx.setFontSize(30);
					ctx.setFillStyle('#FF4778');
					ctx.setTextAlign('left');
					ctx.fillText(name, 75, 987);
					ctx.save();
				}

				console.log("路径", arr2[3])

				ctx.drawImage(arr2[3], 26, 1102, 400, 90);
				ctx.save();
				ctx.setFontSize(30);
				ctx.setFillStyle('#999');
				ctx.fillText('长按图片识别右侧小程序码查看', 230, 1263);
				ctx.save();
				let r = 90;
				let d = r * 2;
				let cx = 525;
				let cy = 1080;
				ctx.drawImage(arr2[2], cx, cy, d, d);
				ctx.restore();
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						fileType: 'png',
						success: function(res) {
							uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		});
		const sysInfo = wx.getSystemInfoSync();
		const screenWidth = sysInfo.screenWidth;
		let factor = screenWidth / 750;

		function toPx(rpx) { // rpx转px
			return rpx * factor;
		}

		function toRpx(px) { // px转rpx
			return px / factor;
		}

		function _drawRadiusRect(x, y, w, h, r, ctx) {
			const br = r / 2;
			ctx.beginPath();
			ctx.moveTo(toPx(x + br), toPx(y)); // 移动到左上角的点
			ctx.lineTo(toPx(x + w - br), toPx(y)); // 画上边的线
			ctx.arcTo(toPx(x + w), toPx(y), toPx(x + w), toPx(y + br), toPx(br)); // 画右上角的弧		
			ctx.lineTo(toPx(x + w), toPx(y + h - br)); // 画右边的线
			ctx.arcTo(toPx(x + w), toPx(y + h), toPx(x + w - br), toPx(y + h), toPx(br)); // 画右下角的弧
			ctx.lineTo(toPx(x + br), toPx(y + h)); // 画下边的线
			ctx.arcTo(toPx(x), toPx(y + h), toPx(x), toPx(y + h - br), toPx(br)); // 画左下角的弧
			ctx.lineTo(toPx(x), toPx(y + br)); // 画左边的线
			ctx.arcTo(toPx(x), toPx(y), toPx(x + br), toPx(y), toPx(br)); // 画左上角的弧
		}
	},
	PosterCanvas2: function(arr,name, successFn) {
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: arr[0],
			success: function(res) {
				ctx.drawImage(res.path, 0, 0, 702, 1128);
				ctx.save();
				ctx.drawImage(arr[2], 32, 915, 48, 48);
				ctx.save();
				ctx.setFillStyle('#1F1F1F');
				ctx.setFontSize(32)
				ctx.fillText(name, 96, 948);
				ctx.save();
				ctx.setFillStyle('#FF6933');
				ctx.setFontSize(24)
				ctx.fillText('扫码直接办理，流程便捷，当天到账。', 32, 1012);
				ctx.save();
				ctx.drawImage(arr[1], 32, 1052, 32, 16);
				ctx.save();
				ctx.restore()
				ctx.drawImage(arr[3], 494, 920, 168, 168);
				ctx.save();
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						fileType: 'png',
						success: function(res) {
							console.log("获取信息",res)
							uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		});
	},
	/**
	 * 获取砍价/拼团海报
	 * @param array arr2 海报素材 背景图
	 * @param string store_name 素材文字
	 * @param string price 价格
	 * @param string ot_price 原始价格
	 * @param function successFn 回调函数
	 * 
	 * 
	 */
	bargainPosterCanvas: function(arr2, title, label, msg, price, wd, hg, successFn) {
		let that = this;
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		ctx.fillStyle = '#fff';
		ctx.fillRect(0, 0, wd * 2, hg * 2);
		uni.getImageInfo({
			src: arr2[0],
			success: function(res) {
				const WIDTH = res.width;
				const HEIGHT = res.height;
				ctx.drawImage(arr2[0], 0, 0, wd, hg);

				// 保证在不同机型对应坐标准确
				let labelx = 0.6500 //标签x
				let labely = 0.166 //标签y
				let pricex = 0.1857 //价格x
				let pricey = 0.180 //价格x
				let codex = 0.385 //二维码
				let codey = 0.77
				let picturex = 0.1571 //商品图左上点
				let picturey = 0.2916
				let picturebx = 0.6857 //商品图右下点
				let pictureby = 0.3916
				let msgx = 0.1036 //msg
				let msgy = 0.2306
				let codew = 0.25
				ctx.drawImage(arr2[1], wd * picturex, hg * picturey, wd * picturebx, hg * pictureby);
				ctx.drawImage(arr2[2], wd * codex, hg * codey, wd * codew, wd * codew);
				ctx.save();
				//标题
				const CONTENT_ROW_LENGTH = 30;
				let [contentLeng, contentArray, contentRows] = that.textByteLength(title,
					CONTENT_ROW_LENGTH);
				if (contentRows > 2) {
					contentRows = 2;
					let textArray = contentArray.slice(0, 2);
					textArray[textArray.length - 1] += '…';
					contentArray = textArray;
				}
				ctx.setTextAlign('left');
				ctx.setFillStyle('#000');
				if (contentArray.length < 2) {
					ctx.setFontSize(22);
				} else {
					ctx.setFontSize(20);
				}
				let contentHh = 8;
				for (let m = 0; m < contentArray.length; m++) {
					if (m) {
						ctx.fillText(contentArray[m], 20, 35 + contentHh * m + 18, 1100);
					} else {
						ctx.fillText(contentArray[m], 20, 35, 1100);
					}
				}
				// 标签内容
				ctx.setTextAlign('left')
				ctx.setFontSize(16);
				ctx.setFillStyle('#FFF');
				ctx.fillText(label, wd * labelx, hg * labely);
				ctx.save();
				// 价格
				ctx.setFillStyle('red');
				ctx.setFontSize(26);
				ctx.fillText(price, wd * pricex, hg * pricey);
				ctx.save();
				// msg
				ctx.setFillStyle('#333');
				ctx.setFontSize(16);
				ctx.fillText(msg, wd * msgx, hg * msgy);
				ctx.save();
				ctx.draw(true, () => {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						fileType: 'png',
						quality: 1,
						success: (res) => {
							successFn && successFn(res.tempFilePath);
							uni.hideLoading();
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},
	/**
	 * 用户信息分享海报
	 * @param array arr2 海报素材  1背景 0二维码
	 * @param string nickname 昵称
	 * @param string sitename 价格
	 * @param function successFn 回调函数
	 * 
	 * 
	 */
	userPosterCanvas: function(arr2, nickname, sitename, index, w, h, successFn) {
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas' + index);
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: arr2[1],
			success: function(res) {
				const WIDTH = res.width;
				const HEIGHT = res.height;
				console.log("邀请海报", WIDTH, HEIGHT)
				ctx.fillStyle = '#fff';
				ctx.fillRect(0, 0, w, h);
				ctx.drawImage(arr2[1], 0, 0, w, h);
				ctx.setTextAlign('left')
				ctx.setFontSize(12);
				ctx.setFillStyle('#333');

				// x:240 y:426
				let codex = 0.1906
				let codey = 0.7946
				let codeSize = 0.21666
				let namex = 0.4283
				let namey = 0.8215
				let markx = 0.4283
				let marky = 0.8685
				ctx.drawImage(arr2[0], w * codex, h * codey, w * codeSize, w * codeSize);
				if (w < 270) {
					ctx.setFontSize(8);
				} else {
					ctx.setFontSize(10);
				}
				ctx.fillText(nickname, w * namex, h * namey);
				if (w < 270) {
					ctx.setFontSize(8);
				} else {
					ctx.setFontSize(10);
				}
				ctx.fillText('邀请您加入' + sitename, w * markx, h * marky);
				ctx.save();
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas' + index,
						fileType: 'png',
						quality: 1,
						success: function(res) {
							uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},
	// 绘制文本，并处理超出部分
	drawText(text, x, y, maxWidth,ctx) {
	  let textWidth = ctx.measureText(text).width;
	
	  if (textWidth <= maxWidth) {
	    // 文本宽度未超出最大宽度，直接绘制
	    ctx.fillText(text, x, y);
	  } else {
	    // 文本宽度超出最大宽度，需要截取并添加省略号
	    let ellipsis = '...';
	    let ellipsisWidth = ctx.measureText(ellipsis).width;
	
	    let len = text.length;
	    while (textWidth + ellipsisWidth > maxWidth && len > 0) {
	      len--;
	      text = text.slice(0, len);
	      textWidth = ctx.measureText(text).width;
	    }
	
	    // 绘制带省略号的文本
	    ctx.fillText(text + ellipsis, x, y);
	  }
	},
	groupPoster(arr, index, successFn) {
		let that = this;
		console.log("下标==", arr[0], arr[1])
		const ctx = uni.createCanvasContext('myCanvas' + index);
		ctx.clearRect(0, 0, 0, 0);



		uni.getImageInfo({
			src: arr[0],
			success(res) {
				console.log("图片信息==", res.path)
				ctx.fillStyle = '#fff';
				ctx.fillRect(0, 0, 1400, 840);
				ctx.drawImage(res.path, 212, 0, 280, 280);
				ctx.save();
				uni.getImageInfo({
					src: arr[1],
					success(result) {
						console.log("图片信息==", res.height)
						ctx.drawImage(result.path, 24, 328, result.width, result.height);
						ctx.save();
						ctx.draw(true, function() {
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas' + index,
								fileType: 'png',
								quality: 1,
								success: function(result2) {
									console.log("测试结果==", result2)
									uni.hideLoading();
									successFn && successFn(result2
										.tempFilePath);
								},
								fail(err) {
									uni.hideLoading();
								}
							})
						});
					}
				})
			}
		})
	},
	// 封装的绘制圆角矩形的方法
	drawRoundedRect(canvas, x, y, width, height, borderRadius) {
		// 绘制圆角矩形路径
		canvas.beginPath();
		canvas.moveTo(x + borderRadius, y);
		canvas.lineTo(x + width - borderRadius, y);
		canvas.arcTo(x + width, y, x + width, y + borderRadius, borderRadius);
		canvas.lineTo(x + width, y + height - borderRadius);
		canvas.arcTo(x + width, y + height, x + width - borderRadius, y + height, borderRadius);
		canvas.lineTo(x + borderRadius, y + height);
		canvas.arcTo(x, y + height, x, y + height - borderRadius, borderRadius);
		canvas.lineTo(x, y + borderRadius);
		canvas.arcTo(x, y, x + borderRadius, y, borderRadius);
		canvas.closePath();

		canvas.clip(); // 剪切路径
	},
	//团购预览
	wxPreviewPoster(arr, price, successFn) {
		let that = this;
		const ctx = uni.createCanvasContext('myCanvas1');
		uni.getImageInfo({
			src: arr[0],
			success(res) {
				ctx.fillStyle = '#fff';
				ctx.fillRect(0, 0, res.width, res.height);
				console.log("信息==", res)
				ctx.drawImage(res.path, 0, 0, res.width, res.height);
				ctx.save();
				// fillRoundRect: function(cxt, x, y, width, height, radius, /*optional*/ fillColor) 
				that.drawRoundedRect(ctx, 40, 136, 258, 258, 16)
				ctx.drawImage(arr[1], 40, 136, 258, 258);
				ctx.restore();
				ctx.save();
				ctx.setTextAlign('left')
				ctx.setFontSize(64);
				ctx.setFillStyle('#EB4D42');
				ctx.fillText(price.replace(/\.00$/, ''), 340, 220);
				ctx.save();
				ctx.setFontSize(32);
				ctx.fillText('元起', 415, 215);
				ctx.save();
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas1',
						fileType: 'png',
						quality: 1,
						success: function(result2) {
							console.log("图片信息444==", arr[1])
							console.log("测试结果==", result2)
							uni.hideLoading();
							successFn && successFn(result2
								.tempFilePath);
						},
						fail(err) {
							console.log("失败原因", err)
							uni.hideLoading();
						}
					})
				});
			}
		})
	},
	//团购海报
	teamPosterCanvas(arr,time,group_title,min_price,max_price,group_name,canvasId ,successFn) {
		uni.showLoading({
			title:"海报生成中"
		})
		let that = this;
		console.log("参数==",canvasId)
		let canvasIds = canvasId?canvasId:'myCanvas'
		const ctx = uni.createCanvasContext(canvasIds)
		ctx.clearRect(0, 0, 574, 978);
		ctx.fillStyle = '#fff';
		ctx.fillRect(0, 0, 574, 978);
		ctx.drawImage(arr[1], 24, 24, 68, 68);
		ctx.save();
		ctx.setTextAlign('left');
		ctx.setFontSize(28);
		ctx.setFillStyle('#1F1F1F');
		 ctx.setTextBaseline('top'); // 设置文本基线为顶部
		ctx.fillText(group_name, 108, 24);
		ctx.setFontSize(24);
		ctx.setFillStyle('#999999');
		ctx.fillText(time, 108, 68);
		ctx.save();
		that.drawRoundedRect(ctx,24, 116, 526, 526,16);
		ctx.drawImage(arr[2], 24, 116, 526, 526);
		ctx.restore()
		ctx.save();
		ctx.setFontSize(32);
		ctx.setFillStyle('#1F1F1F');
		that.drawText(group_title, 24, 674,550,ctx)
		// ctx.fillText(group_title, 24, 674);
		ctx.setFontSize(24);
		ctx.setFillStyle('#999999');
		ctx.fillText('靠谱团购、高品质商品、跟团购更实惠！', 24, 738);
		ctx.setFontSize(36);
		ctx.setFillStyle('#F22718');
		ctx.fillText(`￥${min_price}-${max_price}`, 24, 854);
		ctx.save();
		ctx.drawImage(arr[0], 24, 912, 322, 40);
		ctx.drawImage(arr[3], 398, 802, 144, 144);
		ctx.save();
		
		ctx.draw(true, function() {
			uni.canvasToTempFilePath({
				canvasId:canvasIds,
				fileType: 'png',
				quality: 1,
				success: function(result2) {
					uni.hideLoading();
					successFn && successFn(result2
						.tempFilePath);
				},
				fail(err) {
					console.log("失败原因", err)
					uni.hideLoading();
				}
			})
		});
	},
	wxPreviewPoster1(arr, nickname, successFn) {
		let that = this;
		const ctx = uni.createCanvasContext('myCanvas2');
		console.log("结果===", arr[0], nickname)
		ctx.filter = 'blur(8px)';
		ctx.drawImage(arr[0], 0, 0, 542, 434);
		ctx.save();
		// 设置矩形的宽度和高度
		const width = 526;
		const height = 92;
		that.drawRoundedRect(ctx,8, 334, width, height,16)
		// 绘制矩形的背景
		ctx.filter = 'blur(100px)';
		ctx.setFillStyle('rgba(0,0,0,0.4)');
		ctx.fillRect(8, 334, width, height);

		// 设置模糊效果
		// ctx.setGlobalAlpha(0.8); // 控制透明度
		// ctx.setShadow(0, 0, 8, 'rgba(0, 0, 0, 0.12)'); // 添加阴影效果
		ctx.save()
		that.drawRoundedRect(ctx,32, 356, 44, 44,8);
		ctx.drawImage(arr[2], 32, 356, 44, 44);
		ctx.restore()
		ctx.save()
		ctx.setTextAlign('left')
		ctx.setFontSize(28);
		ctx.setFillStyle('#FFFFFF');
		ctx.fillText(nickname, 84, 387);
		ctx.save();
		ctx.drawImage(arr[1], 326, 334, 208, 92);
		ctx.save()

		ctx.draw(true, function() {
			uni.canvasToTempFilePath({
				canvasId: 'myCanvas2',
				fileType: 'png',
				quality: 1,
				success: function(result2) {
					console.log("测试结果==", result2)
					uni.hideLoading();
					successFn && successFn(result2
						.tempFilePath);
				},
				fail(err) {
					console.log("失败原因", err)
					uni.hideLoading();
				}
			})
		});
	},
	wxPreviewPoster2(arr, nickname, successFn) {
		let that = this;
		const ctx = uni.createCanvasContext('myCanvas3');
		console.log("结果===", arr[0], nickname)
		ctx.filter = 'blur(8px)';
		ctx.drawImage(arr[0], 0, 0, 542, 434);
		ctx.save();
		ctx.drawImage(arr[1], 16, 16, 330, 402);
		ctx.save();
		const centerX = 40; // 圆心的X坐标
		const centerY = 40; // 圆心的Y坐标
		const radius = 16; // 圆的半径

		// 绘制圆形路径
		ctx.beginPath();
		ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
		ctx.closePath();
		ctx.clip(); // 剪切路径

		// 绘制图片（假设imgUrl为图片的链接）
		ctx.drawImage(arr[2], centerX - radius, centerY - radius, radius * 2, radius * 2);
		// ctx.drawImage(arr[2], 24, 24, 32, 32);
		ctx.restore();
		ctx.save();
		ctx.setTextAlign('left')
		ctx.setFontSize(24);
		ctx.setFillStyle('#FFFFFF');
		ctx.fillText(nickname, 64, 48);
		ctx.save();

		ctx.draw(true, function() {
			uni.canvasToTempFilePath({
				canvasId: 'myCanvas3',
				fileType: 'png',
				quality: 1,
				success: function(result2) {
					console.log("测试结果==", result2)
					uni.hideLoading();
					successFn && successFn(result2
						.tempFilePath);
				},
				fail(err) {
					console.log("失败原因", err)
					uni.hideLoading();
				}
			})
		});
	},
	/*促销海报*/
	salesPosterCanvas: function(arr2, index, w, h, successFn) {
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas' + index);
		ctx.clearRect(0, 0, 0, 0);
		console.log('111')
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: arr2[2],
			success: function(res) {

				// ctx.fillStyle = '#fff';
				// ctx.fillRect(0, 0, w, h);
				ctx.drawImage(arr2[2], 0, 0, w, h - 150);
				console.log("高度=====", h - 150)
				console.log('222', w, h)
				// x:240 y:426
				let codex = 0.6606
				let codey = 0.7846
				let codeSize = 0.28666
				let namex = 0.4283
				let namey = 0.8215
				let markx = 0.4283
				let marky = 0.8685
				ctx.drawImage(arr2[1], 0, h - 180, w, 170);
				ctx.drawImage(arr2[0], w * codex, h * codey, w * codeSize, w *
					codeSize);
				ctx.save();

				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas' + index,
						fileType: 'png',
						quality: 1,
						success: function(res) {
							uni.hideLoading();
							successFn && successFn(res
								.tempFilePath);
						},
						fail(err) {
							uni.hideLoading();
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},
	groupPosterCanvas: function(imageUrl, bottomUrl, w, h, successFn) {
		let that = this;
		console.log("进入测试图", imageUrl, bottomUrl)
		// uni.showLoading({
		// 	title: '分享图生成中',
		// 	mask: true
		// });
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: imageUrl,
			success: function(res) {
				console.log(res)
				ctx.drawImage(res.path, 0, 0, 230, 184);
				ctx.save();
				uni.getImageInfo({
					src: bottomUrl,
					success(result) {
						ctx.drawImage(result.path, 0, 130, 230, 54);
						ctx.save();

						console.log('222', result)
						ctx.draw(true, function() {
							console.log('333')
							uni.canvasToTempFilePath({
								canvasId: 'myCanvas',
								fileType: 'png',
								quality: 1,
								width: w,
								height: h,
								success: function(result2) {
									console.log("测试3", result2)
									uni.hideLoading();
									successFn && successFn(result2
										.tempFilePath);
								},
								fail(err) {
									console.log(err, "报错信息")
									uni.hideLoading();
								}
							})
						});
					}
				})
			},
			fail: function(err) {
				console.log("报错欣喜222", err)
				uni.hideLoading();
				// that.Tips({
				// 	title: '无法获取图片信息'
				// });
			}
		})
	},
	/**
	 * 邀请好友分享海报
	 * @param array arr2 海报素材  1背景 0二维码
	 * @param string nickname 昵称
	 * @param function successFn 回调函数
	 * 
	 * 
	 */
	friendPosterCanvas: function(arr2, w, h, successFn) {
		console.log("图片路径", arr2[0], arr2[1])
		let that = this;
		uni.showLoading({
			title: '海报生成中',
			mask: true
		});
		const ctx = uni.createCanvasContext('myCanvas');
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: arr2[1],
			success: function(res) {
				const WIDTH = res.width;
				const HEIGHT = res.height;
				console.log("图片信息", res)
				// ctx.fillStyle = '#fff';
				// ctx.fillRect(0, 0, WIDTH, HEIGHT);
				ctx.drawImage(res.path, 0, 0, WIDTH, HEIGHT);
				// ctx.save();
				// ctx.setTextAlign('left')
				// ctx.setFontSize(12);
				// ctx.setFillStyle('#333');
				console.log("第一步")
				// x:240 y:426
				// let codex = 0.1906
				// let codey = 0.7746
				// let codeSize = 0.21666
				// let namex = 0.4283
				// let namey = 0.8215
				// let markx = 0.4283
				// let marky = 0.8685
				ctx.drawImage(arr2[0], WIDTH / 2 - 124, HEIGHT / 2 + 124, 248, 248);
				console.log("第二步")
				// if (w < 270) {
				// 	ctx.setFontSize(8);
				// } else {
				// 	ctx.setFontSize(10);
				// }
				// ctx.fillText(nickname, w * namex, h * namey);
				// if (w < 270) {
				// 	ctx.setFontSize(8);
				// } else {
				// 	ctx.setFontSize(10);
				// }
				// ctx.fillText('邀请您加入' + sitename, w * markx, h * marky);
				ctx.save();
				console.log("第三步")
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						fileType: 'png',
						width: WIDTH,
						height: HEIGHT,
						destWidth: WIDTH,
						destHeight: HEIGHT,
						quality: 1,
						success: function(res) {
							console.log("第四步")
							uni.hideLoading();
							successFn && successFn(res.tempFilePath);
						},
						fail(err) {
							console.log("写入失败", err)
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	},
	/*
	 * 单图上传
	 * @param object opt
	 * @param callable successCallback 成功执行方法 data 
	 * @param callable errorCallback 失败执行方法 
	 */
	uploadImageOne: function(opt, successCallback, errorCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'],
			is_load = opt.is_load || true,
			uploadUrl = opt.url || '',
			inputName = opt.name || 'pics',
			fileType = opt.fileType || 'image';
		uni.chooseImage({
			count: count, //最多可以选择的图片总数  
			sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: function(res) {
				//启动上传等待中...  
				uni.showLoading({
					title: '图片上传中',
				});
				uni.uploadFile({
					url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
					filePath: res.tempFilePaths[0],
					fileType: fileType,
					name: inputName,
					formData: {
						'filename': inputName
					},
					header: {
						// #ifdef MP
						"Content-Type": "multipart/form-data",
						// #endif
						[TOKENNAME]: 'Bearer ' + store.state.app.token
					},
					success: function(res) {
						uni.hideLoading();
						if (res.statusCode == 403) {
							that.Tips({
								title: res.data
							});
						} else if (res.statusCode == 413) {
							that.Tips({
								title: '上传图片失败,请重新上传小尺寸图片'
							});
						} else {
							let data = res.data ? JSON.parse(res.data) : {};
							if (data.status == 200) {
								successCallback && successCallback(data)
							} else {
								errorCallback && errorCallback(data);
								that.Tips({
									title: data.msg
								});
							}
						}
					},
					fail: function(res) {
						uni.hideLoading();
						that.Tips({
							title: '上传图片失败'
						});
					}
				})
			}
		})
	},
	/*
	 * 单图上传压缩版
	 * @param object opt
	 * @param callable successCallback 成功执行方法 data 
	 * @param callable errorCallback 失败执行方法 
	 */
	uploadImageChange: function(opt, successCallback, errorCallback, sizeCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'],
			is_load = opt.is_load || true,
			uploadUrl = opt.url || '',
			inputName = opt.name || 'pics',
			fileType = opt.fileType || 'image';
		uni.chooseImage({
			count: count, //最多可以选择的图片总数  
			sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: function(res) {
				//启动上传等待中...  
				let imgSrc
				let objImg = res.tempFilePaths;
				objImg.forEach(item => {
					uni.getImageInfo({
						src: item,
						success(ress) {
							uni.showLoading({
								title: '图片上传中',
							});
							if (res.tempFiles[0].size <= 2097152) {
								uploadImg(ress.path)
								return
							}
							// uploadImg(canvasPath.tempFilePath)
							let canvasWidth, canvasHeight, xs, maxWidth = 750
							xs = ress.width / ress.height // 宽高比例
							if (ress.width > maxWidth) {
								canvasWidth = maxWidth // 这里是最大限制宽度
								canvasHeight = maxWidth / xs
							} else {
								canvasWidth = ress.width
								canvasHeight = ress.height
							}
							sizeCallback && sizeCallback({
								w: canvasWidth,
								h: canvasHeight
							})
							let canvas = uni.createCanvasContext('canvas');
							canvas.width = canvasWidth
							canvas.height = canvasHeight
							canvas.clearRect(0, 0, canvasWidth, canvasHeight);
							canvas.drawImage(ress.path, 0, 0, canvasWidth, canvasHeight)
							canvas.save();
							// 这里的画布drawImage是一种异步属性  可能存在未绘制全就执行了draw的问题  so添加延迟
							setTimeout(e => {
								canvas.draw(true, () => {
									uni.canvasToTempFilePath({
										canvasId: 'canvas',
										fileType: 'JPEG',
										destWidth: canvasWidth,
										destHeight: canvasHeight,
										quality: 0.7,
										success: function(
											canvasPath) {
											uploadImg(
												canvasPath
												.tempFilePath
											)
										}
									})
								});
							}, 200)


						}
					})
				})
			}
		})

		function uploadImg(filePath) {
			uni.uploadFile({
				url: HTTP_REQUEST_URL + '/api/' + uploadUrl,
				filePath,
				fileType: fileType,
				name: inputName,
				formData: {
					'filename': inputName
				},
				header: {
					// #ifdef MP
					"Content-Type": "multipart/form-data",
					// #endif
					[TOKENNAME]: 'Bearer ' + store.state.app.token
				},
				success: function(res) {
					uni.hideLoading();
					if (res.statusCode == 403) {
						that.Tips({
							title: res.data
						});
					} else {
						let data = res.data ? JSON.parse(res.data) : {};
						if (data.status == 200) {
							successCallback && successCallback(data)
						} else {
							errorCallback && errorCallback(data);
							that.Tips({
								title: data.msg
							});
						}
					}
				},
				fail: function(res) {
					uni.hideLoading();
					that.Tips({
						title: '上传图片失败'
					});
				}
			})
		}
	},

	/**
	 * 处理服务器扫码带进来的参数
	 * @param string param 扫码携带参数
	 * @param string k 整体分割符 默认为：&
	 * @param string p 单个分隔符 默认为：=
	 * @return object
	 * 
	 */
	// #ifdef MP
	getUrlParams: function(param, k, p) {
		if (typeof param != 'string') return {};
		k = k ? k : '&'; //整体参数分隔符
		p = p ? p : '='; //单个参数分隔符
		var value = {};
		if (param.indexOf(k) !== -1) {
			param = param.split(k);
			for (var val in param) {
				if (param[val].indexOf(p) !== -1) {
					var item = param[val].split(p);
					value[item[0]] = item[1];
				}
			}
		} else if (param.indexOf(p) !== -1) {
			var item = param.split(p);
			value[item[0]] = item[1];
		} else {
			return param;
		}
		return value;
	},
	// #endif
	/*
	 * 合并数组
	 */
	SplitArray(list, sp) {
		if (typeof list != 'object') return [];
		if (sp === undefined) sp = [];
		for (var i = 0; i < list.length; i++) {
			sp.push(list[i]);
		}
		return sp;
	},
	trim(backUrlCRshlcICwGdGY) {
		return String.prototype.trim.call(backUrlCRshlcICwGdGY);
	},
	$h: {
		//除法函数，用来得到精确的除法结果
		//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
		//调用：$h.Div(arg1,arg2)
		//返回值：arg1除以arg2的精确结果
		Div: function(arg1, arg2) {
			arg1 = parseFloat(arg1);
			arg2 = parseFloat(arg2);
			var t1 = 0,
				t2 = 0,
				r1, r2;
			try {
				t1 = arg1.toString().split(".")[1].length;
			} catch (e) {}
			try {
				t2 = arg2.toString().split(".")[1].length;
			} catch (e) {}
			r1 = Number(arg1.toString().replace(".", ""));
			r2 = Number(arg2.toString().replace(".", ""));
			return this.Mul(r1 / r2, Math.pow(10, t2 - t1));
		},
		//加法函数，用来得到精确的加法结果
		//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
		//调用：$h.Add(arg1,arg2)
		//返回值：arg1加上arg2的精确结果
		Add: function(arg1, arg2) {
			arg2 = parseFloat(arg2);
			var r1, r2, m;
			try {
				r1 = arg1.toString().split(".")[1].length
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length
			} catch (e) {
				r2 = 0
			}
			m = Math.pow(100, Math.max(r1, r2));
			return (this.Mul(arg1, m) + this.Mul(arg2, m)) / m;
		},
		//减法函数，用来得到精确的减法结果
		//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
		//调用：$h.Sub(arg1,arg2)
		//返回值：arg1减去arg2的精确结果
		Sub: function(arg1, arg2) {
			arg1 = parseFloat(arg1);
			arg2 = parseFloat(arg2);
			var r1, r2, m, n;
			try {
				r1 = arg1.toString().split(".")[1].length
			} catch (e) {
				r1 = 0
			}
			try {
				r2 = arg2.toString().split(".")[1].length
			} catch (e) {
				r2 = 0
			}
			m = Math.pow(10, Math.max(r1, r2));
			//动态控制精度长度
			n = (r1 >= r2) ? r1 : r2;
			return ((this.Mul(arg1, m) - this.Mul(arg2, m)) / m).toFixed(n);
		},
		//乘法函数，用来得到精确的乘法结果
		//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
		//调用：$h.Mul(arg1,arg2)
		//返回值：arg1乘以arg2的精确结果
		Mul: function(arg1, arg2) {
			arg1 = parseFloat(arg1);
			arg2 = parseFloat(arg2);
			var m = 0,
				s1 = arg1.toString(),
				s2 = arg2.toString();
			try {
				m += s1.split(".")[1].length
			} catch (e) {}
			try {
				m += s2.split(".")[1].length
			} catch (e) {}
			return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
		},
	},
	// 获取地理位置;
	$L: {
		async getLocation() {
			// #ifdef APP-PLUS
			let status = await this.checkPermission();
			if (status !== 1) {
				return;
			}
			// #endif
			// #ifdef MP-WEIXIN || MP-TOUTIAO || MP-QQ
			let status = await this.getSetting();
			if (status === 2) {
				this.openSetting();
				return;
			}
			// #endif

			this.doGetLocation();
		},
		doGetLocation() {
			uni.getLocation({
				success: (res) => {
					uni.removeStorageSync('CACHE_LONGITUDE');
					uni.removeStorageSync('CACHE_LATITUDE');
					uni.setStorageSync('CACHE_LONGITUDE', res.longitude);
					uni.setStorageSync('CACHE_LATITUDE', res.latitude);
				},
				fail: (err) => {
					// #ifdef MP-BAIDU
					if (err.errCode === 202 || err.errCode === 10003) { // 202模拟器 10003真机 user deny
						this.openSetting();
					}
					// #endif
					// #ifndef MP-BAIDU
					if (err.errMsg.indexOf("auth deny") >= 0) {
						uni.showToast({
							title: "访问位置被拒绝"
						})
					} else {
						uni.showToast({
							title: err.errMsg
						})
					}
					// #endif
				}
			})
		},
		getSetting: function() {
			return new Promise((resolve, reject) => {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.userLocation'] === undefined) {
							resolve(0);
							return;
						}
						if (res.authSetting['scope.userLocation']) {
							resolve(1);
						} else {
							resolve(2);
						}
					}
				});
			});
		},
		openSetting: function() {
			uni.openSetting({
				success: (res) => {
					if (res.authSetting && res.authSetting['scope.userLocation']) {
						this.doGetLocation();
					}
				},
				fail: (err) => {}
			})
		},
		async checkPermission() {
			let status = permision.isIOS ? await permision.requestIOS('location') :
				await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');

			if (status === null || status === 1) {
				status = 1;
			} else if (status === 2) {
				uni.showModal({
					content: "系统定位已关闭",
					confirmText: "确定",
					showCancel: false,
					success: function(res) {}
				})
			} else if (status.code) {
				uni.showModal({
					content: status.message
				})
			} else {
				uni.showModal({
					content: "需要定位权限",
					confirmText: "设置",
					success: function(res) {
						if (res.confirm) {
							permision.gotoAppSetting();
						}
					}
				})
			}
			return status;
		},
	}

}